import requests
import json
import time
import urllib3
# 禁用安全请求警告
urllib3.disable_warnings(urllib3.exceptions.InsecurePlatformWarning)

data = {}
# 传递流程参数，调用时可以更改参数值，也可以不传递参数，将使用默认值
# 例如，参数名为table，值为t_movies_ratings, 则参数传递为：
# params['table'] = 't_movies_ratings'
params = {}
<#list serviceParams as param>
<#if param.paramName != '' && param.paramName != 'system.appId' && param.paramType != 'datasource'>
params['${param.paramName}'] = '${param.paramValue}'
</#if>
</#list>

# header中传递App-Key和App-Token，其中App-Token是使用AppSecret和Public Key(公钥)进行RSA加密产生
headers = {}
<#if token ??>
headers["App-Key"] = "${token.key}"
headers["App-Token"] = "RSA(AppSecret + '-' + new Date().getTime(), Public Key)"
# 获取App-Token
getTokenUrl = '${urlPrefix}/api/ai/platform/service/gen-token'
tokenParams = {'text': '${token.secret}'}
resDict = requests.post(getTokenUrl, params=tokenParams, verify=False)
contentDict = json.loads(str(resDict.content, encoding='utf8'))
headers["App-Token"] = contentDict['data']

headers["Content-Type"] = "application/json;charset=UTF-8"
</#if>

# 1.调用执行方法execute
asyncExecuteUrl = "${urlPrefix}/webapi/ai/model/async/execute/${service.id}"
res = requests.post(asyncExecuteUrl,headers=headers,data=json.dumps(data), verify=False)
result = json.loads(str(res.content, encoding='utf8'))
print(res.text)
# 获取eid， 在后续调用中会使用到
eid = result['data']['eid']

# 2.调用状态查询方法status
data = {}
data['eid'] = eid
# 3.查询服务运行状态
asyncStatusUrl = "${urlPrefix}/webapi/ai/model/async/status/${service.id}"
res = ""
flag: bool = True
while flag:
    time.sleep(2)
    <#if token ??>
    # 重新获取获取App-Token
    getTokenUrl = '${urlPrefix}/api/ai/platform/service/gen-token'
    tokenParams = {'text': '${token.secret}'}
    resDict = requests.post(getTokenUrl, params=tokenParams, verify=False)
    contentDict = json.loads(str(resDict.content, encoding='utf8'))
    headers["App-Token"] = contentDict['data']
    headers["Content-Type"] = "application/json;charset=UTF-8"
    </#if>
    res = requests.post(asyncStatusUrl, headers=headers, params=data, verify=False)
    print(res.text)
    statusRes = json.loads(str(res.content, encoding='utf8'))
    statusData = statusRes.get("data")
    if statusData is not None:
        status = statusData['status']
        # 服务状态为FINISHED KILLED FAILED结束
        if status == 'FINISHED' or status == 'KILLED' or status == 'FAILED':
            flag = False
    else:
        flag = False

print(res.text)
